//
//  GSLoginViewController.swift
//  SinaWeiboDay1
//
//  Created by SamuelChan on 16/4/9.
//  Copyright © 2016年 SamuelChan. All rights reserved.
//

import UIKit
import SVProgressHUD
class GSLoginViewController: UIViewController {
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavigationButton()
        loadWebView()
        
    }
    //MARK: - 私有方法
    private func loadWebView(){
        
//        https://api.weibo.com/oauth2/authorize?client_id=2208906532&redirect_uri=http://www.baidu.com
        let link :String = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url : NSURL = NSURL(string: link)!
        let request : NSURLRequest = NSURLRequest(URL: url)
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("正在拼命加载中...", maskType:.None)

    }
    
    private func setupNavigationButton() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: Selector("autoFillButtonDidClick"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: Selector("cancel"))
    }
    
    @objc private func autoFillButtonDidClick(){
        let js = "document.getElementById('userId').value = 'hurry002@163.com';document.getElementById('passwd').value = 'Acerko11,'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
    }

    
    //MARK: - 懒加载
    lazy var webView = UIWebView()
}


/**使用拓展来管理代理*/

extension GSLoginViewController : UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*GSLoginViewController.swift,[65]行,方法名称：webView(_:shouldStartLoadWithRequest:navigationType:)输出: Optional("http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")
        GSLoginViewController.swift,[67]行,方法名称：webView(_:shouldStartLoadWithRequest:navigationType:)输出: Optional("http://www.baidu.com/?code=335a10a29bf647ba4ac58ad195e35e86")*/
        let urlString = request.URL?.absoluteString
        let isRedirectURL = urlString!.hasPrefix(redirect_uri)
        
        if !isRedirectURL {
            return true
        }else{
            //query是get请求?后面的东西
            let query = request.URL?.query
            let codeString = "code="
            if query!.hasPrefix(codeString){
                //授权按钮被点击了
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                GSPrint("code:\(code)")
            }else {
                cancel()
            }
        }
        
        
        GSPrint(request.URL?.absoluteString)
        return true
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.showErrorWithStatus("网络不给力啊!")
    }
    

}